//
//  NewCloudReserveController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/27.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class MyCloudDetailController: BaseViewController {
    
    var handlerClosure: (() -> Void)?
    
    private let orderId: String
    
    init(with orderId: String) {
        self.orderId = orderId
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var detailViewModel: MyCloudDetailViewModel?
    
    private var readmeViewMode: MyCloudReadMeDetailViewModel? {
        didSet {
            tableView.isHidden = false
            agreeBtn.isHidden = false
            agreeLabel.isHidden = false
            payBtn.isHidden = false
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadData()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupNotification()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    @IBOutlet weak var agreeBtn: UIButton! {
        didSet {
            agreeBtn.isHidden = true
        }
    }
    @IBOutlet weak var agreeLabel: UIButton! {
        didSet {
            agreeLabel.isHidden = true
        }
    }
    

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .background
            tableView.isHidden = true
            tableView.tableFooterView = UIView()
            tableView.register(PublishHeaderViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishHeaderViewCell.reuseIdentifier())
            tableView.register(PublishLabelViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishLabelViewCell.reuseIdentifier())
            tableView.register(PublishTextViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishTextViewCell.reuseIdentifier_0)
            tableView.register(PublishButtonViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishButtonViewCell.reuseIdentifier())
            tableView.register(PublishTextViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishTextViewCell.reuseIdentifier_1)
            tableView.register(PublishTextViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishTextViewCell.reuseIdentifier_2)
            tableView.register(PublishImageViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishImageViewCell.reuseIdentifier())
            tableView.register(NewSectionHeaderView.nibForCell(),
                               forHeaderFooterViewReuseIdentifier: NewSectionHeaderView.reuseIdentifier())
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(endEditing))
            tap.cancelsTouchesInView = false
            tableView.addGestureRecognizer(tap)
        }
    }
    
    @IBOutlet private weak var payBtn: UIButton! {
        didSet {
            payBtn.eventInterval = 2.0
            payBtn.setBackgroundImage(UIImage(color: .mainColor), for: .normal)
            payBtn.setBackgroundImage(UIImage(color: .mainLight), for: .highlighted)
            payBtn.setBackgroundImage(UIImage(color: .mainLight), for: .disabled)
            payBtn.isHidden = true
        }
    }
    
    private var isAgree: Bool = false
}

// MARK: - Action
extension MyCloudDetailController {
    @IBAction private func viewAgreementAction(_ sender: UIButton) {
        let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
        agreementView.show(type: .informedLetter)
    }
    
    @IBAction private func agreeAction(_ sender: UIButton) {
        sender.isSelected.toggle()
        isAgree = sender.isSelected
    }
    
    @IBAction private func payAction(_ sender: UIButton) {
        if !isAgree {
            HUDTool.show(message: "确定知情同意书及平台免责声明")
            return
        }
        
        if let vm = detailViewModel {
            wechatSubmitOrder(vm)
        }
    }
    
    @objc private func endEditing() {
        tableView.endEditing(true)
    }
    
    /// 选择支付方式
    private func showSelectPayStyleView(_ model: WXPayResult) {
//        let payVm = PayViewModel(order: model)
        let styleView = UINib.loadViewFrom(SelectPayStyleView.self)
        styleView.show()
        styleView.configure(cost: model.ownAmount, time: "30")
        styleView.handlerClosure = { [weak self] style in
            switch style {
            case .wechat:
                self?.wechatPay(model)
            }
        }
    }
    
    /// 微信支付
    private func wechatSubmitOrder(_ vm: MyCloudDetailViewModel) {
        HUDTool.showActivity()
        WXApiRequestHandler.wxPaySubmitOrder(orderId: orderId,
                                             orderAmount: vm.orderAmount,
                                             orderType: .cloud,
                                             success: { wxModel in
            HUDTool.hideActivity()
            switch wxModel.getType {
            case 1:
                self.showSelectPayStyleView(wxModel)
            case 4:
                HUDTool.show(message: "医保已全额支付")
                self.pushPayResultVc()
            default:
                break
            }
        }) { (errorMsg, code) in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    /// 微信支付
    private func wechatPay(_ model: WXPayResult) {
        if !WXApi.isWXAppInstalled() {
            HUDTool.show(message: "未安装微信")
            return
        }
        
        WXApiRequestHandler.generateWXPayOrder(model: model)
    }
    
    @objc private func wechatPaySuccess(_ noti: Notification) {
        HUDTool.showActivity()
        PayViewModel.queryOrderStatus(orderId: orderId) { (errorMsg) in
            HUDTool.hideActivity()
            if errorMsg != nil {
                HUDTool.show(message: "订单支付失败")
                self.navigationController?.popViewController(animated: true)
            } else {
                self.pushPayResultVc()
            }
        }
    }
    
    @objc private func wechatPayFailure(_ noti: Notification) {
        HUDTool.show(message: "订单支付失败")
        navigationController?.popViewController(animated: true)
    }
    
    private func pushPayResultVc() {
        if let pubViewModel = self.detailViewModel?.publishViewModel {
            let payResultVc = PayResultViewController(with: pubViewModel, orderType: .cloud)
            navigationController?.pushViewController(payResultVc, animated: true)
            payResultVc.handlerClosure = { [weak self] in
                guard let self = self else { return }
                self.handlerClosure?()
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
}

extension MyCloudDetailController {
    private func setupUI() {
        title = "预约云门诊"
    }
    
    private func setupNotification() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(wechatPaySuccess(_:)),
                                               name: NotiName.wechatPaySuccess,
                                               object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(wechatPayFailure(_:)),
                                               name: NotiName.wechatPayFailure,
                                               object: nil)
    }
}

extension MyCloudDetailController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 6
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0: return 3
        case 1: return 2
        case 3: return readmeViewMode?.isAllergyHistory == true ? 2 : 1
        default: return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            return firstSectionCell(at: indexPath)
        case 1:
            return secondSectionCell(at: indexPath)
        case 2:
            return thirdSectionCell(at: indexPath)
        case 3:
            return fourthSectionCell(at: indexPath)
        case 4:
            return fifthSectionCell(at: indexPath)
        case 5:
            return sixthSectionCell(at: indexPath)
        default:
            return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0: return indexPath.row == 0 ? 96 : 44
        case 1: return 44
        case 2: return 150
        case 3: return indexPath.row == 0 ? 44 : 80
        case 4: return 100
        case 5: return 250
        default: return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 2, 4, 5:
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: NewSectionHeaderView.reuseIdentifier()) as? NewSectionHeaderView
            header?.configure(at: section, title: "届时请提前打开APP等候")
            return header
        default:
            return UIView()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 0:
            let footer = UINib.loadViewFrom(YSGPublishRuleView.self)
            footer.configure(with: .cloud)
            return footer
        default: return nil
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0: return 78
        default: return 0.001
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0: return 0.001
        case 2: return 56
        case 4, 5: return 36
        default: return 16
        }
    }
}

// MARK: - init cell
extension MyCloudDetailController {
    private func firstSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishHeaderViewCell.reuseIdentifier(),
                                                                 for: indexPath) as! PublishHeaderViewCell
            if let vm = self.detailViewModel {
                cell.updateData(with: vm)
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishLabelViewCell.reuseIdentifier(),
                                                                 for: indexPath) as! PublishLabelViewCell
            
            if let vm = self.detailViewModel {
                cell .updateData(vm: vm, indexPath: indexPath)
            }
            return cell
        }
    }
    
    private func secondSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishLabelViewCell.reuseIdentifier(),
                                                 for: indexPath) as! PublishLabelViewCell
        if let vm = detailViewModel {
            cell.updateData(vm: vm, indexPath: indexPath)
        }
        return cell
    }
    
    private func thirdSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishTextViewCell.reuseIdentifier_0) as! PublishTextViewCell
        if let readMe = self.readmeViewMode {
            cell.updateData(for: indexPath, vm: readMe)
        }
        return cell
    }
    
    private func fourthSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishButtonViewCell.reuseIdentifier(),
                                                     for: indexPath) as! PublishButtonViewCell
            if let vm = readmeViewMode {
                cell.update(cloudOrder: vm)
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishTextViewCell.reuseIdentifier_1,
                                                     for: indexPath) as! PublishTextViewCell
            if let readMe = self.readmeViewMode {
                cell.updateData(for: indexPath, vm: readMe)
            }
            return cell
        }
    }
    
    private func fifthSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishTextViewCell.reuseIdentifier_2,
                                                 for: indexPath) as! PublishTextViewCell
        if let readMe = self.readmeViewMode {
            cell.updateData(for: indexPath, vm: readMe)
        }
        return cell
    }
    
    private func sixthSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishImageViewCell.reuseIdentifier(),
                                                 for: indexPath) as! PublishImageViewCell
        if let vm = readmeViewMode {
            let imageModels = vm.resultList.map { model -> UploadImgModel in
                return UploadImgModel(resourceId: model.resourceId,
                                      ShareThumbnailUrl: model.thumbnailUrl,
                                      shareThumbnailUrl: model.thumbnailUrl,
                                      shareUrl: model.url)
            }
            let publishVm = PublishViewModel(models: imageModels, deleteEnabled: false)
            cell.configure(with: publishVm, delegate: nil)
        }
        return cell
    }
}

// MARK: - 网络请求
private extension MyCloudDetailController {
    func loadData() {
        HUDTool.showActivity()
        MyCloudDetailViewModel.getCloudOrderDetail(orderId: self.orderId, success: { (model) in
            HUDTool.hideActivity()
            self.detailViewModel = MyCloudDetailViewModel(model: model)
            self.loadPatientReadMeDetail(diagonoseId: model.diagnoseId ?? "")
        }) { (errorMsg) in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    func loadPatientReadMeDetail(diagonoseId: String) {
        HUDTool.showActivity()
        MyCloudReadMeDetailViewModel.getCloudPatientReadMeDetail(diagnoseId: diagonoseId, success: { (model) in
            HUDTool.hideActivity()
            self.readmeViewMode = MyCloudReadMeDetailViewModel(model: model)
        }) { (errorMsg) in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
        }
    }
    
}
